/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package db

import (
	"did-service/common/constant"
	"math"
)

type Page struct {
	PageNum  int         `json:"pageNum"`
	PageSize int         `json:"pageSize"`
	Total    int64       `json:"totalCount"`
	Pages    int         `json:"pages"`
	List     interface{} `json:"list,omitempty"`
}

func NewPage(total int64, pageNum int) *Page {
	return &Page{
		PageNum:  pageNum,
		PageSize: 10,
		Total:    total,
		Pages:    0,
		List:     []struct{}{},
	}
}

func (p *Page) SetPageSize(pageSize int) *Page {
	if pageSize <= 0 {
		pageSize = 10
	}
	p.PageSize = pageSize
	return p
}

func (p *Page) SetTotal(total int64) *Page {
	p.Total = total
	return p
}

func (p *Page) SetPageNo(pageNum int) *Page {
	p.PageNum = pageNum
	return p
}

func (p *Page) CreatePage(data interface{}) *Page {
	p.Pages = int(math.Ceil(float64(p.Total) / float64(p.PageSize)))
	p.SetData(data)
	return p
}

func (p *Page) SetData(data interface{}) *Page {
	if data != nil {
		p.List = data
	}
	return p
}

func (p *Page) OutBorder() bool {
	return p.Total <= int64((p.PageNum-1)*p.PageSize)
}

func (p *Page) PageOffset() int {
	return (p.PageNum - 1) * p.PageSize
}

func (p *Page) OrmLimit() (int, int) {
	return p.PageSize, p.PageOffset()
}

func OnePage(pageNo, pageSize int, total int64, bean interface{}) *Page {
	if pageSize <= 0 {
		pageSize = constant.DefaultPageSize
	} else if pageSize > constant.MaxPageSize {
		pageSize = constant.MaxPageSize
	}
	return NewPage(total, pageNo).SetPageSize(pageSize).CreatePage(bean)
}
